import config from '@/config/index';

interface Result<T> {
  msg: string,
  code: number,
  data: T
}

class Http {
  private static instance: Http | null = null;

  private constructor() {}

  static getInstance() {
    if (!Http.instance) {
      Http.instance = new Http();
    }
    return Http.instance;
  }


  request<T = any>(option: WechatMiniprogram.RequestOption): Promise<Result<T>> {
    return new Promise((resolve, reject) => {
      wx.request({
        ...option,
        url: config.baseUrl + '/' + option.url,
        header: {
          Authorization: wx.getStorageSync('token')
        },
        success(res: WechatMiniprogram.RequestSuccessCallbackResult<Result<T>>) {
          switch (res.data.code) {
            case 200:
              resolve(res.data);
              break;
            case 401:
              const token = wx.getStorageSync('token')
              wx.redirectTo({
                url: "/pages/login/index"
              })
              if(token) wx.$toast(res.data.msg);
              wx.removeStorageSync("token")
            break;
            case 500:
              wx.$toast(res.data.msg);
              break;
            default:
              break;
          }
        },
        fail(e) {
          reject(e);
        },
      });
    });
  }
}

export default Http.getInstance().request;